<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>数据表数据</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../static/lib/layui-v2.6.3/css/layui.css" media="all">
    <!-- <link rel="stylesheet" href="../css/layui.css"> -->
    <link rel="stylesheet" href="../static/css/public.css" media="all">
    <style>
        .title title {
            display: block;
            align-content: center;
            
        }
        title {
            font-size: large;
            color: #07a;
            font-weight: 800;
            letter-spacing: 2px;
            font-size: 20px;
            background: white;
            margin: 0 auto;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
    
        <a href="" id="downloadLink" style="display:none;"></a>
        <script type="text/html" id="formTableToolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm" lay-event="excel"> 导出数据</button>
                <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="flush"> 刷新</button>
                <button class="layui-btn layui-btn-sm  layui-btn-normal " lay-event="files"> 打包文件 </button>
            </div>
        </script>
        <div class="title" align="center">
            <title>{{classesID}} 班级数据表</title>
        </div>
        <table class="layui-hide" id="formTableId" lay-filter="formTableFilter" ></table>

        <script type="text/html" id="formTableBar">
            <!-- <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a> -->
            <a class="layui-btn layui-btn-normal layui-btn-xs layui-btn-warm " lay-event="download">下载</a>
        </script>
        <a id="downloadtag" stype="display:none;" href="" ></a>
        
    </div>
</div>
<script src="../static/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<!-- <script src="../js/layui.js"></script> -->
<script src="../static/js/axios.min.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table', 'laydate','laytpl'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            laydate = layui.laydate,
            laytpl = layui.laytpl;
        var fieldMap={};

        // laytpl.config({
        //     open: '<%',
        //     close: '%>'
        // });
        var classesID = parseInt("{{classesID}}")
        var tableID = parseInt("{{tableID}}");

        console.log("tableID", tableID);
        table.render({
            elem: '#formTableId',
            url: '/formData/getFormTable',
            cellMinWidth: 80,
            where:{
                tableID:tableID,
                class: parseInt("{{classesID}}")
            },
            toolbar: '#formTableToolbarDemo',
            defaultToolbar: ['filter',{
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            escape: true,
            cols: [[
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 50,
            page: true,
            skin: 'line'
        });
        
    function flush_table(){
        console.log("flush");
        var cur =  $(".layui-laypage-skip").find("input").val(); 
        var limit = $(".layui-laypage-limits").find("option:selected").val();
        table.reload('formTableId', {
                page: {
                    curr: cur,
                    limit:limit
                }
            });
    }

        // get formID
    function gen_fields(){

        axios.get('/formData/getFormTable?tableID='+tableID).then(function (response) {
            console.log("response", response);
            var formField = response.data.fields;
            console.log("formField", formField);
    
            var select_form = $("#post_formID");
            var cols = [
                {type: "checkbox", width: 50},
                {type: "numbers", width: 50}
            ];
            var s;
            fieldMap = {}
            for (var i=0; i<formField.length; ++i){
                fieldMap[formField[i][0]] = formField[i].slice(1,4);
                if (formField[i][3] == "text"){
                    cols.push({field: formField[i][0], hide: formField[i][0]==="classesID"?true:false ,width: formField[i][2], title: formField[i][1], sort: true})
                } else if (formField[i][3] == "upload"){
                    s = '<div><button lay-submit class="layui-btn layui-btn-normal layui-btn-xs" fid="'+decodeURI('%7B%7B')+'d.'+formField[i][0]+decodeURI('%7D%7D')+'" lay-filter="show_file">在线预览</button></div>'
                    // s = '';
                    cols.push({field: formField[i][0], width: formField[i][2], align: "center", title: formField[i][1], templet: s})
                }
            }
            cols.push({title: '操作', fixed: 'right' ,wdth: 80, toolbar: '#formTableBar', align: "right"})
            
            console.log("cols", cols);
            console.log("fieldMap", fieldMap);

            // 设置搜索栏选择字段功能
            var self_select = $("#self_select");
            var ele;
            for (var k in fieldMap){
                ele = document.createElement("option");
                ele.value = k;
                ele.text = fieldMap[k][0];
                self_select.append(ele);
            }
            form.render();
            

            table.render({
                elem: '#formTableId',
                url: '/formData/getFormTable',
                toolbar: '#formTableToolbarDemo',
                where:{
                    tableID:tableID,
                    class: parseInt("{{classesID}}")
                },
                defaultToolbar: ['filter',{
                    title: '提示',
                    layEvent: 'LAYTABLE_TIPS',
                    icon: 'layui-icon-tips'
                }],
                cols: [cols],
                escape: true,
                cellMinWidth: 80,
                limits: [10, 15, 20, 25, 50, 100],
                limit: 50,
                page: true,
                skin: 'line',
                done: function (){
                    var btn_no_files = $("button[fid=null]");
                    console.log("btn_no_files ", btn_no_files);
                    for (var i=0; i<btn_no_files.length; ++i){
                        btn_no_files[i].outerHTML= `<button lay-submit class="layui-btn layui-btn-warm layui-btn-xs">未提交</button>`;

                    }
                }
            });

        })
        }
        gen_fields();
        flush_table();
        /**
         * toolbar监听事件
         */
        table.on('toolbar(formTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '上传文件',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '../page/filesupload.html',
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('formTableId')
                    , data = checkStatus.data;
                // layer.alert(JSON.stringify(data));
                // console.log(data,data.length);
                if (data.length==0) {layer.msg("请选中一个元素进行删除");return false;}
                layer.confirm("确定要删除？",function(index){
                    // console.log(obj);
                    // console.log(data);
                    data0 = {
                        tableID:tableID,
                        stuIDs:[]
                    }
                    for(var i=0; i< data.length; ++i){
                        data0.stuIDs.push(data[i].stuID)
                    }
                    
                    var cur =  $(".layui-laypage-skip").find("input").val(); 
                    var limit = $(".layui-laypage-limits").find("option:selected").val();
                    
                    axios.post('/formData/delFormTablePostDatas', data0)
                    .then(function (response) {
                        // console.log(response);
                        layui.table.reload('formTableId',{
                            where: {
                                page:cur,
                                limit:limit,
                                tableID:tableID
                            }
                            ,page: {
                                curr: cur //重新从当前 页开始
                            }
                        });
                        
                        
                        layer.msg("数据删除成功!",{icon:1});
                    }).catch(function (error) {
                        layer.msg("数据删除失败!",{icon:2});
                    }); 	
                    layer.close(index);
                });
            } else if (obj.event == "files") {
                var checkStatus = table.checkStatus('formTableId')
                    , data = checkStatus.data;
                console.log("data", data);
                var postData = {data:[]};
                if (data.length > 0) {
                    for (var k in fieldMap) {
                        if (fieldMap[k][2] === "upload"){
                            for (var i=0; i<data.length; ++i){
                                postData.data.push(data[i][k]);
                            }
                        }
                    }
                    postData["type"] = "selected";
                } else {
                    postData["type"] = "all";
                }
                postData["tableID"] = tableID;
                postData["classesID"] = classesID;
                console.log("postData", postData);

                
                axios.post('/formData/downloadFormPostFile', postData)
                    .then(function (res) {
                        // obj.del();
                        console.log(res);
                        // 文件下载
                        var a = $("#downloadLink")[0];
                        a.href = "/formData/downloadZipFile?filename="+res.data.filename;
                        console.log("a.href ", a.href,a);
                        a.click();
                        // layer.msg("!",{icon:1});

                    }).catch(function (error) {
                        layer.msg("文件获取失败!",{icon:2});
                    }); 	
            } else if (obj.event === "excel") {  // 导出Excel表格
                var checkStatus = table.checkStatus('formTableId')
                    , data = checkStatus.data;
                console.log("data", data);
                console.log("obj", obj);
                console.log("fieldMap", fieldMap);
                var postData = {data:data, cols:[]};
                // console.log("postData ", postData);
                var op_cols =  obj.config.cols[0].slice(2,  obj.config.cols[0].length-1)
                for (var i in op_cols) {
                    console.log(op_cols[i]);
                    postData.cols.push([op_cols[i].field, op_cols[i].title, fieldMap[op_cols[i].field][2]]);
                }
                if (data.length > 0) {
                    postData["type"] = "selected";
                } else {
                    postData["type"] = "all";
                }
                postData["tableID"] = tableID;
                postData["classesID"] = classesID;
                console.log("postData", postData);
                
                axios.post('/formData/exportTableData', postData)
                    .then(function (res) {
                        // obj.del();
                        console.log(res);
                        // 文件下载
                        var a = $("#downloadLink")[0];
                        a.href = "/formData/downloadExcel?filename="+res.data.filename;
                        console.log("a.href ", a.href,a);
                        a.click();
                        // layer.msg("!",{icon:1});

                    }).catch(function (error) {
                        layer.msg("文件获取失败!",{icon:2});
                    }); 
            } else if (obj.event === "flush") {
                flush_table();
            }
        });
        
        table.on('tool(formTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                console.log("data",data);
                // console.log("obj",obj);
                // var data_  = Object.assign({}, data);
                // delete data_[""]

                // console.log("save fieldMap ", fieldMap);

                var index = layer.open({
                    title: '修改提交数据',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '../page/table/edit_formPostData.html',
                    success:function (layero, index) {
                    //打开子窗口后通过success赋值,两个变量基本是固定写法
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']];

                        console.log(data.content);
                        
                        //给子窗口中的元素赋值
                        body.find('input[name="fileID"]').val(data.fileID);
                        body.find('input[name="userFileName"]').val(data.userFileName);
                        body.find('textarea[name="beizhu"]').val(data.beizhu);

                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('是否删除数据', function (index) {
                    console.log(obj);
                    data["tableID"] = tableID;
                    console.log("data",data);
                    axios.post('/formData/delFormTablePostData', data)
                    .then(function (response) {
                        obj.del();
                        layer.msg("数据删除成功!",{icon:1});
                    }).catch(function (error) {
                        layer.msg("数据删除失败!",{icon:2});
                    }); 	
                    layer.close(index);

                });
            } else if (obj.event === "download") {
                console.log(obj);
                console.log(fieldMap);
                var postData = {data:[]};
                for (var k in fieldMap) {
                    if (fieldMap[k][2] === "upload"){
                        postData.data.push(data[k])
                    }
                }
                postData["type"] = "selected";
                postData["tableID"] = tableID;
                console.log("postData", postData);
                
                axios.post('/formData/downloadFormPostFile', postData)
                    .then(function (res) {
                        // obj.del();
                        console.log(res);
                        // 文件下载
                        var a = $("#downloadLink")[0];
                        a.href = "/formData/downloadZipFile?filename="+res.data.filename;
                        console.log("a.href ", a.href,a);
                        a.click();
                        // layer.msg("!",{icon:1});

                    }).catch(function (error) {
                        layer.msg("文件获取失败!",{icon:2});
                    }); 	

            } 
        });

        form.on('submit(show_file)', function (data) {
            console.log("click", data);
            var fid = data.elem.getAttribute("fid")
            var index = layer.open({
                    title: '上传文件',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '/to_html?id='+fid,
                });
        });

        setInterval(flush_table, 60000);
    });
</script>

</body>
</html>